# -*- coding: utf-8 -*-
import requests
from django.forms import model_to_dict

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import json
import requests
from common.log import logger
from common.mymako import render_mako_context
from .forms import UploadFileForm
from models import UrlManager


@csrf_exempt
def proxy(request, uid, path):
    """
    首页
    """
    manager = UrlManager.objects.get(id=uid)
    s = "/proxy/%s" % uid
    purl = manager.purl
    url = "/" + path
    proxy_reuqest_url = purl + url
    meta = request.META
    request_headers = {}
    for k, v in meta.items():
        if k == 'HTTP_HOST':
            k.replace("HTTP_", "").replace("_", "-").lower()
        elif k.startswith("HTTP_"):
            request_headers[k.replace("HTTP_", "").replace("_", "-").lower()] = v
    try:
        if request.method == 'GET':
            response = requests.get(url=proxy_reuqest_url,
                                    headers=request_headers, params=request.META['QUERY_STRING'])

        elif request.method == 'HEAD':
            response = requests.head(url=proxy_reuqest_url,
                                     headers=request_headers)

        elif request.method == "POST":
            for k, v in meta.items():
                if "CONTENT_TYPE" in k:
                    request_headers[k.replace("_", "-").lower()] = v
            if "json" in (request_headers["content-type"] + ""):
                body = request.body
                response = requests.post(url=proxy_reuqest_url,
                                         headers=request_headers, json=json.loads(body),
                                         params=request.META['QUERY_STRING'])
            elif "form-data" not in (request_headers["content-type"] + ""):
                body = request.body
                response = requests.post(url=proxy_reuqest_url,
                                         headers=request_headers, data=body, params=request.META['QUERY_STRING'])
            else:
                form = UploadFileForm(request.POST, request.FILES)
                file = form.files
                body = form.data
                del request_headers['content-type']
                response = requests.post(url=proxy_reuqest_url,
                                         headers=request_headers, files=file, data=body,
                                         params=request.META['QUERY_STRING'])

        elif request.method == "DELETE":
            response = requests.delete(url=proxy_reuqest_url,
                                       headers=request_headers)

        elif request.method == "PUT":
            body = request.body
            response = requests.put(url=proxy_reuqest_url,
                                    headers=request_headers, data=body)

        else:
            return False, None

    except requests.exceptions.RequestException as e:

        body = request.body
        logger.exception(
            "login http request error! type: %s, url: %s, data: %s, exception: %s" % (request.method, proxy_reuqest_url, body,e))
        return False, None
    sbody = response.content
    response_headers = response.headers
    response.close()
    new_response = HttpResponse(content=sbody, status=response.status_code)
    for k, v in response_headers.items():
        k = str(k).lower()
        if (not k == 'connection') and (not k == 'keep-alive') and (not k == 'proxy-authenticate') and (
        not k == 'proxy-authenrization') and (not k == 'trailer') and (not k == 'te') and (
        not k == 'transfer-encoding') and (not k == 'upgrade'):
            new_response[k] = v
    return new_response


def homepage(request):
    """
    首页
    """

    managers = UrlManager.objects.filter(status=0)
    res = {
        'managers': [
            {
                "id": m.id,
                "pname": m.pname,
                "purl": m.purl,
            } for m in managers
        ]

    }

    return render_mako_context(request, '/home_application/homepage.html', res)


def delete(request, id):
    """
    联系我们
    """
    store = UrlManager.objects.get(id=id)
    delete = store.delete()
    managers = UrlManager.objects.filter(status=0)
    res = {
        'managers': [
            {
                "id": m.id,
                "pname": m.pname,
                "purl": m.purl,
            } for m in managers
        ]

    }
    return render_mako_context(request, '/home_application/homepage.html', res)


@csrf_exempt
def add(request):
    if request.method == 'POST':
        nname = request.POST['nname']
        nurl = request.POST['nurl']
        UrlManager.objects.create(pname=nname, purl=nurl)
    managers = UrlManager.objects.filter(status=0)
    res = {
        'managers': [
            {
                "id": m.id,
                "pname": m.pname,
                "purl": m.purl,
            } for m in managers
        ]

    }
    return render_mako_context(request, '/home_application/homepage.html', res)


@csrf_exempt
def edit(request, id):
    """
    联系我们
    """

    UrlManager.objects.filter(id=id).update(pname=request.POST['nname'], purl=request.POST['nurl'])
    managers = UrlManager.objects.filter(status=0)
    res = {
        'managers': [
            {
                "id": m.id,
                "pname": m.pname,
                "purl": m.purl,
            } for m in managers
        ]

    }
    return render_mako_context(request, '/home_application/homepage.html', res)
